/*
 *  Author: zhaijl 
 *  Url: http://218.1.73.212/down.php
 *  Country: China
 *  
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software based apache mina 2.0 and spring 3.0
 *
 */
package org.cloudy.http.conf ;

import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import org.cloudy.http.codec.ContentType;

public class ContextLoader {
	private static Map < String, Context > ctx_map = new HashMap < String, Context > () ;
	private static Map < String, String > flt_map = new HashMap< String, String > () ;
	private static int BUFFER_SIZE = 1024 ;
	private static int SERVER_PORT = 80 ;
	private static int SERVER_MAXB = 1024 ;
	private static int SERVER_MINB = 1024 ;

	private static String WEBROOT_DIR = "" ;
	
	private static Random random = new Random () ;
	
	public static int BUFFER_SIZE () {  return BUFFER_SIZE;  }
	public static int SERVER_PORT () {  return SERVER_PORT;  }
	public static String WEBROOT_DIR () {  return WEBROOT_DIR;  }

	public static int SERVER_MAXB () {  return SERVER_MAXB;  }
	public static int SERVER_MINB () {  return SERVER_MINB;  }
	
	public static boolean initialize ( InputStream is ) throws Exception {
		try {		
			System.setProperty ( "javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" ) ;
			System.setProperty ( "javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl" ) ;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance () ;
		    dbf.setNamespaceAware ( false ) ; 
		    dbf.setValidating ( false ) ;
		    DocumentBuilder db = dbf.newDocumentBuilder () ;
		    Document document = db.parse ( is ) ;	
		    Element eleRoot = document.getDocumentElement () ;
		    ContextLoader.BUFFER_SIZE = Integer.parseInt ( eleRoot.getAttribute ( "size" ) ) ;
		    ContextLoader.SERVER_PORT = Integer.parseInt ( eleRoot.getAttribute ( "port" ) ) ;
		    ContextLoader.SERVER_MAXB = Integer.parseInt ( eleRoot.getAttribute ( "maxb" ) ) ;
		    ContextLoader.SERVER_MINB = Integer.parseInt ( eleRoot.getAttribute ( "minb" ) ) ;
		    
		    ContextLoader.WEBROOT_DIR = eleRoot.getAttribute ( "path" ) ;
		    
		    NodeList rootChildren = eleRoot.getElementsByTagName ( "ctx" ) ;
		    for ( int i = 0;  i < rootChildren.getLength (); i++ ) {    	
		    	Element cxtEle = ( Element )rootChildren.item ( i ) ;
		    	Context ctxObject = new Context () ;
		    	ctxObject.setName ( cxtEle.getAttribute ( "name" ) ) ;
		    	ctxObject.setPath ( cxtEle.getAttribute ( "path" ) ) ;
		    	
		    	if ( ctxObject.getName () == null || ctxObject.getName ().trim ().length () <= 0 ||
		    			ctxObject.getPath () == null || ctxObject.getPath ().trim ().length () <= 0 ) {
		    		return false ;
		    	}
		    	
		    	NodeList listFilter = cxtEle.getElementsByTagName ( "filter" ) ;
		    	for ( int j = 0;  j < listFilter.getLength (); j++ ) {
		    		Element eleFilter = ( Element )listFilter.item ( j ) ;
		    		String strName = eleFilter.getAttribute ( "name" ) ;
		    		String strClid = eleFilter.getAttribute ( "clid" ) ;
		    		if ( strName == null || strName.trim ().length () <= 0 ||
		    				strClid == null || strClid.trim ().length () <= 0 ) {
		    			return false ;
		    		}		    		
		    		//ctxObject.setFilter ( strName, strClid ) ;
		    		flt_map.put ( strName, strClid ) ;
		    	}
		    	ctx_map.put ( ctxObject.getName (), ctxObject ) ;
		    }		    
		    return true ;
		} catch ( Exception exc ) { 
			throw exc ;
		} finally {
			System.getProperties ().remove ( "javax.xml.parsers.DocumentBuilderFactory" ) ;
			System.getProperties ().remove ( "javax.xml.parsers.SAXParserFactory" ) ;			
		}			
	}
	
	public static Context getContext ( String context ) {
		Context object = ctx_map.get ( context ) ;
		if ( object == null ) object = new Context ( "resfile", context ) ;
		return object ;
	}	
	
	public static String getSessionId ( Long id ) {
		return new StringBuffer ( id.toString () ).append ( System.currentTimeMillis () ).append ( random.nextInt ( 1000 ) ).toString () ;
	}
	
	public static String getContentType ( String key ) {
		if ( key == null )  return "text/html" ;
		String value = ContentType.get ( key ) ;
		return value == null ? "text/html" : value ;
	}
	
	public static String getContextPath ( String childpath, String filename ) {
		StringBuffer sb = new StringBuffer () ;
		sb.append ( ContextLoader.WEBROOT_DIR ) ;
		sb.append ( childpath ) ;
		sb.append ( filename ) ;
		return sb.toString () ;
	}
	
	public static String getFilter ( String context ) {
		return flt_map.get ( context ) ;
	}	
	
	public static String getFirstURL ( String url ) {
		StringBuffer sb = new StringBuffer () ;
		sb.append ( "http://127.0.0.1:" ).append ( SERVER_PORT () ) ;
		sb.append ( "/" ).append ( url ) ;
		return sb.toString () ;		
	}
}